//
//  CLRefresh_02.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/17.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
//定义下拉刷新块的高度
private let CLRefreshHeight :CGFloat = 50
//定义下来刷新三种状态的枚举
enum CLRefreshType :Int{
    case normal
    case pulling
    case refreshing
}

class CLRefresh_02: UIControl {

    //定义当前默认为下拉刷新状态
    var refreshStatu :CLRefreshType = .normal {
        didSet {
            switch refreshStatu {
            case .normal:
                //下拉刷新
            arrorImageView.hidden = false
                messageLabel.text = "下拉刷新"
                inteditorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrorImageView.transform = CGAffineTransformIdentity
                })
                //只有上一次是刷新状态 才回到原始看不见的位置
            if oldValue == .refreshing {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top -= CLRefreshHeight
                })
            }
            case .pulling:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrorImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .refreshing:
                messageLabel.text = "正在刷新"
                arrorImageView .hidden = true
                inteditorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += CLRefreshHeight
                })
                //告诉外界刷新, 只有继承了UIControl才能发送时间
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
   
    
    
    //懒加载控件
    private lazy var arrorImageView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字控件
    private lazy var messageLabel:UILabel = {
        let label = UILabel ()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.orangeColor()
        label.textAlignment = .Center
        return label
    }()
    //风火轮
    private lazy var inteditorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    //重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 设置约束
    private func setUpUI() {
        
        addSubview(arrorImageView)
        addSubview(messageLabel)
        addSubview(inteditorView)
        //设置元素
        //关闭自动约束
        arrorImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: arrorImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: arrorImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        //文字
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute:.Leading, relatedBy: .Equal, toItem: arrorImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: arrorImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        //风火轮
        inteditorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: inteditorView, attribute:.CenterX, relatedBy: .Equal, toItem: arrorImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: inteditorView, attribute: .CenterY, relatedBy: .Equal, toItem: arrorImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
    }
    //定义当前滚动的视图
    var currentScrollView:UIScrollView?
    //将要添加到哪个父控件的时候去调动
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }//设置自己的Frame
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: CLRefreshHeight)
        self.frame.origin.y = -CLRefreshHeight
        //使用kvo监听事件的发生
        scrollView.addObserver(self, forKeyPath: "contenOffset", options:[.New], context: nil )
        currentScrollView = scrollView
    }
    
    //监听方法实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        guard let scrollView = currentScrollView else {
            return
        }
        if scrollView.dragging {
            if scrollView.contentOffset.y < -114 && refreshStatu == .normal {
                //将模式设置为松手刷新
                refreshStatu = .pulling
            }else if scrollView.contentOffset.y > -114 && refreshStatu == .pulling {
                refreshStatu = .normal
            }
        }else {
            if refreshStatu == .pulling {
                refreshStatu = .refreshing
            }
        }
    }
    
    //结束刷新
    func endRefresh() {
        refreshStatu = .normal
    }
    //移除kvo
    deinit{
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
    
    
}
